import store from "../../../../store/index";

export default class SocketService {
  static instance = null;
  static get Instance() {
    if (!this.instance) {
      this.instance = new SocketService();
    }
    return this.instance;
  }
  // 和服务端连接的socket对象
  ws = null;
  // 存储回调函数
  callBackMapping = {};
  // 标识是否连接成功
  connected = false;
  // 记录重试的次数
  sendRetryCount = 0;
  // 重新连接尝试的次数
  connectRetryCount = 0;
  // 心跳定时器
  heartbeatTimer = null;

  // 重连定时器
  reconectTimer = null;

  // 连接服务器
  connect() {
    if (!window.WebSocket) {
      return console.log("您的浏览器不支持WebSocket");
    }
    const url = store.getters.returnConfig.org.websocket.message;
    this.ws = new WebSocket(url);
    // 连接成功的事件
    this.ws.onopen = () => {
      console.log("连接服务端成功了");
      this.setConnentStatus(true);
      this.initSocket();
    };
    // 1.连接服务端失败
    // 2.当连接成功之后, 服务器关闭的情况
    this.ws.onclose = () => {
      console.log("服务端断开链接了");
      this.setConnentStatus(false);
    };
    // 得到服务端发送过来的数据
    this.ws.onmessage = (res) => {
      this.onMessage(JSON.parse(res.data));
    };
  }
  onMessage(msg) {
    // console.log("onMessage", msg);
    const { flag, err_code, org_id } = msg;
    if (
      (flag == "init" || flag == "response" || flag == "heartBeat") &&
      err_code != 1000
    ) {
      // 返回错误码重新init
      setTimeout(() => {
        this.initSocket();
      }, 2000);
    }
    if (!org_id || org_id == store.getters.userInfo.org_id) {
      store.dispatch("SetSocketMessage", msg);
    }
  }
  // 初始化发送数据等
  initSocket() {
    if (this.heartbeatTimer) {
      // 清除之前的心跳定时器
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    }
    const { uid, org_id } = store.getters.userInfo;
    const params = {
      uid,
      org_id,
      client: "web",
    };
    this.send({ flag: "init", ...params });
    this.heartbeatTimer = setInterval(() => {
      this.send({ flag: "heartBeat", ...params });
    }, 5000);
  }
  // 发送数据
  send(data) {
    // 判断此时此刻有没有连接成功
    if (this.connected) {
      try {
        this.ws.send(JSON.stringify(data));
      } catch (e) {
        this.setConnentStatus(false);
      }
    } else {
      this.setConnentStatus(false);
    }
  }
  // 设置当前连接状态
  setConnentStatus(status) {
    this.connected = status;
    if (status == true) {
      //连上了 重置重新连接的次数
      this.connectRetryCount = 0;
    } else {
      // 连接失败 尝试重连
      this.connectRetryCount++;

      // 清除之前的心跳定时器
      if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer);
        this.heartbeatTimer = null;
      }

      // 主动关闭当前websocket
      console.log("status", this.ws.readyState);
      if (
        this.ws.readyState != WebSocket.CLOSING &&
        this.ws.readyState != WebSocket.CLOSED
      ) {
        this.ws.close();
      }

      //重连
      if (this.reconectTimer == null) {
        this.reconectTimer = setTimeout(() => {
          this.reconectTimer = null;
          this.connect();
        }, 2000);
      }
    }
  }
  // 回调函数的注册
  registerCallBack(socketType, callBack) {
    this.callBackMapping[socketType] = callBack;
  }
  // 取消某一个回调函数
  unRegisterCallBack(socketType) {
    this.callBackMapping[socketType] = null;
  }
}
